#pragma once 
#include<iostream>
#include<string>
#include<pthread.h>
#include<functional>

enum class Status
{
    NEW =0,
    RUNNING,
    EXIT
};

using func_t =std::function<void(void*)>;

class Thread
{
public:
    //Thread类封装pthread,构造时传入编号，方法，参数
    Thread(int num=0,func_t func=nullptr,void* args=nullptr)
    :_tid(0),_status(Status::NEW),_func(func),_args(args)
    {
        char name[128];
        snprintf(name,sizeof(name),"thread-%d",num);
        _name=name;
    }
    ~Thread()
    {}

    pthread_t getTID() const{
        return _tid;
    }
    std::string getName() const{
        return _name;
    }
    Status getStatus() const{
        return _status;
    }
    //封装了方法，使传入的回调函数func得以匹配
    static void* runHelper(void* args)
    {
        //func是由ThreadPool封装的void (*threadRoutine)(void*)
        Thread* myThis=static_cast<Thread*>(args);
        myThis->_func(myThis->_args);
    }
    void run()
    {
        int ret=pthread_create(&_tid,nullptr,runHelper,this);
        if(ret!=0)
        {
            std::cerr<<"create thread fail"<<std::endl;
            exit(1);
        }
        _status=Status::RUNNING;
    }
    void join()
    {
        int ret=pthread_join(_tid,nullptr);
        if(ret!=0)
        {
            std::cerr<<"thread join fail"<<std::endl;
            exit(1);
        }
        _status=Status::EXIT;
    }
private:
    pthread_t _tid;
    std::string _name;
    Status _status;
    func_t _func;
    void* _args;
};